var pmd = require('../../template/roll/roll.js')
var app = getApp()
var allReqEnd
Page({
  data: {
    isShow: false,
    swiperinfo: {
      hgt: 0,
      indicatorDots: true,
      autoplay: false,
      dotcolor: 'rgba(0,0,0,0.3)',
      dotactivecolor: '#ffab3a',
      circular: true,
      interval: 5000,
      duration: 300,
    },
    showModel: false,
    banners: [],
    newproducts: [],
    others: [],
    pmd: "0",
    swiperCurrent: 0
  },
  onLoad: function (options) {
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        var swiper_hgt = 420 * res.windowWidth / 750
        var swiperinfo = that.data["swiperinfo"]
        swiperinfo.hgt = swiper_hgt
        that.setData({
          swiperinfo: swiperinfo,
          win_width: res.windowWidth
        })
      },
    })

    app.showLoading()
    app.ready(() => {
      if (app.globalData.address == null) {
        app.showAddressModal()
      } else {
        this.loadData()
      }
    })
  },
  onShow: function () {
    if (this.data.pmd === '1') {
      pmd.run1()
    }
    if (app.globalData.address != null) {
      this.loadData()
    }
  },
  loadData: function () {
    if (app.globalData.address == null) {
      return
    }
    allReqEnd = 0
    this.loadNotice()
    this.loadIndex()
  },
  onHide: function () {
    pmd.stopRun1()
  },
  onUnload: function () {
    pmd.stopRun1()
  },
  onShareAppMessage: function () {

  },
  agreeGetUser: function (e) {
    //设置用户信息本地存储
    try {
      wx.setStorageSync('userInfo', e.detail.userInfo)
    }
    catch (e) {
      app.toast.error('系统提示:网络错误')
    }
    let that = this
    that.setData({
      showModel: false
    })
  },
  swiperChange: function (e) {
    if (e.detail.source === "touch") {
      //防止swiper控件卡死
      if (this.data.current == 0) { // 卡死时，重置current为正确索引
        this.setData({
          swiperCurrent: 0
        })
      }
      else {//正常轮转时，记录正确页码索引
        this.setData({
          swiperCurrent: e.detail.current
        })
      }
    }
  },
  dotTap: function (e) {
    var index = e.currentTarget.id
    this.setData({
      swiperCurrent: index
    })
  },
  paomadeng: function () {
    pmd.run1()
  },
  //加载公告
  loadNotice: function () {
    if (app.globalData.address == null) {
      setTimeout(() => {
        this.loadNotice()
      }, 250)
    }
    else {
      var url = '/yuanmai_we/weapp/banner/get/'
      url = url + app.globalData.address.CITYID
      app.get(url).then(this.loadNoticeCallBack.bind(this))
    }
  },
  loadNoticeCallBack: function (res) {
    var banners = []
    var newproducts = []
    var others = []
    for (var i = 0; i < res.length; i++) {
      res[i].templatedata = JSON.parse(res[i].templatedata)
      if (res[i].bannertype === 0) {
        this.setData({
          pmd: '1'
        })
        pmd.rollInit(this, res[i].templatedata.message)
      }
      else if (res[i].bannertype === 1) {
        banners.push(res[i])
      }
      else if (res[i].bannertype === 2) {
        newproducts.push(res[i])
      }
      else {
        others.push(res[i])
      }
    }

    this.setData({
      banners: banners,
      newproducts: newproducts,
      others: others
    })
    this.paomadeng()
    this.checkRequestEnd()
  },
  //加载热销商品
  loadIndex: function () {
    if (app.globalData.address == null) {
      setTimeout(() => {
        this.loadIndex()
      }, 150)
    }
    else {
      var url = '/yuanmai_we/product/hot/banner/'
      url = url + app.globalData.address.CITYID
      app.get(url).then(this.loadIndexCallBack.bind(this))
    }
  },
  loadIndexCallBack: function (res) {
    this.setData({
      goodsinfos: res
    })
    this.checkRequestEnd()
  },
  checkRequestEnd: function () {
    allReqEnd++
    if (allReqEnd === 2) {
      this.setData({
        isShow: true
      })
      app.hideLoading()
    }
  },
  //跳转到某个热销商品
  toGoods: function (event) {
    var goodsid = event.currentTarget.dataset.goodsid
    var menutype = event.currentTarget.dataset.menutype
    if (menutype === 'NORMAL') {
      goodsid = "bread" + goodsid
      app.globalData.idFlag = goodsid
      wx.switchTab({
        url: '/pages/bread/breadindex'
      })
    }
    else if (menutype === 'mcake') {
      goodsid = "cake" + goodsid
      app.globalData.idFlag = goodsid
      wx.switchTab({
        url: '/pages/cake/cakeindex'
      })
    }
  },
  //跳转到某个新品
  toNewProducts: function (e) {
    var product = e.currentTarget.dataset.product
    var goodsid
    if (product.chainaddress.indexOf('mcake') >= 0) {
      goodsid = "cake" + product.id
      app.globalData.idFlag = goodsid
      wx.switchTab({
        url: '/pages/cake/cakeindex'
      })
    }
    else {
      goodsid = "bread" + product.id
      app.globalData.idFlag = goodsid
      wx.switchTab({
        url: '/pages/bread/breadindex'
      })
    }
  },
  object2Params: function (obj) {
    var ret = []
    if (typeof obj === 'object') {
      for (var i in obj) {
        ret.push(`${i}=${obj[i]}`)
      }
    }
    return ret.join('&')
  },
  bannerAction: function (e) {
    var index = e.currentTarget.dataset.index
    var type = e.currentTarget.dataset.type
    var itemData = this.data[type][index]
    if (itemData) {
      var path = itemData.chainaddress
      switch (itemData.chaintype) {
        case 1: //打开h5页面
          wx.navigateTo({
            url: '../my/stores/stores?url=' + path
          })
          break
        case 2: //打开小程序内部页面
          var tabPages = ["/pages/index/index", "/pages/bread/breadindex", "/pages/cake/cakeindex", "/pages/my/myindex"]
          if (tabPages.includes(path)) {
            wx.switchTab({
              url: `${path}?${this.object2Params(itemData.templatedata)}`
            })
          } else {
            wx.navigateTo({
              url: `${path}?${this.object2Params(itemData.templatedata)}`
            })
          }
          break
        case 3: //打开外部小程序
          wx.navigateToMiniProgram({
            appId: itemData.templatedata.appId,
            path: path && `${path}?${this.object2Params(itemData.templatedata)}`
          })
          break
      }
    }
  },
  showNotice: pmd.showNotice,
  closeNotice: pmd.closeNotice
})
